<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 正文区域 -->
    <el-card class="box-card">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getUserList">
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>

      <!-- 用户列表数据区 -->
      <el-table :data="userList" border stripe>
        <el-table-column label="#" type="index"></el-table-column>
        <el-table-column label="姓名" prop="username"></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="电话" prop="mobile"></el-table-column>
        <el-table-column label="角色" prop="roleName"></el-table-column>
        <el-table-column label="状态" prop="mgStatus">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mgStatus" @change="handleStatusChange(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180px">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="showEditDialog(scope.row.id)"
            ></el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="removeUserInfo(scope.row.id)"
            ></el-button>
            <el-tooltip effect="dark" content="角色分配" placement="top" :enterable="false">
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="showAssignDialog(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[2,5,10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>

    <!-- 添加用户的Dialog -->
    <el-dialog title="添加用户" :visible.sync="addDialogVisible" width="50%" @close="addDailogClosed()">
      <el-form ref="addFormRef" :model="addForm" :rules="addFormRules">
        <!-- 用户名 -->
        <el-form-item label="用户名" label-width="70px" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <!-- 密码 -->
        <el-form-item label="密码" label-width="70px" prop="password">
          <el-input v-model="addForm.password" type="password"></el-input>
        </el-form-item>
        <!-- 手机 -->
        <el-form-item label="手机" label-width="70px" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
        <!-- 邮箱 -->
        <el-form-item label="邮箱" label-width="70px" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑用户信息的Dialog -->
    <el-dialog
      title="编辑用户"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editDialogClosed()"
    >
      <el-form ref="editFormRef" :model="editForm" :rules="editFormRules">
        <!-- 用户名 -->
        <el-form-item label="用户名" label-width="70px" prop="username">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <!-- 手机 -->
        <el-form-item label="手机" label-width="70px" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
        <!-- 邮箱 -->
        <el-form-item label="邮箱" label-width="70px" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUserInfo()">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配角色的Dialog -->
    <el-dialog
      title="分配角色"
      width="50%"
      :visible.sync="setRoleDialogVisible"
      @close="assginDialogClosed()"
    >
      <div>
        <p>当前用户：{{userInfo.username}}</p>
        <p>当前角色：{{userInfo.roleName}}</p>
        <p>
          分配新角色：
          <el-select v-model="selectedRoleId" placeholder="请选择">
            <el-option
              v-for="item in roleList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            ></el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="assignRole()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  created() {
    this.getUserList()
  },
  data() {
    // 验证邮箱规则
    var checkEmail = (rules, value, callback) => {
      const emailReg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
      if (emailReg.test(value)) {
        // 有效邮箱
        return callback()
      }
      callback(new Error('请输入有效邮箱！'))
    }

    // 验证手机规则
    var checkMobile = (rules, value, callback) => {
      const mobileReg = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
      if (mobileReg.test(value)) {
        // 有效手机
        return callback()
      }
      callback(new Error('请输入有效手机！'))
    }
    return {
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 2
      },
      userList: [],
      total: 0,
      addDialogVisible: false,
      addForm: {
        id: 0,
        username: '',
        password: '',
        mobile: '',
        email: ''
      },
      addFormRules: {
        username: [
          { required: true, message: '请输入登录名称', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入登录密码', trigger: 'blur' },
          { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ]
      },
      editForm: {
        username: '',
        mobile: '',
        email: ''
      },
      editDialogVisible: false,
      editFormRules: {
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ]
      },
      setRoleDialogVisible: false,
      userInfo: {},
      roleList: [],
      selectedRoleId: ''
    }
  },
  methods: {
    async getUserList() {
      const { data: result } = await this.$http.get('/users', { params: this.queryInfo })
      if (result.status !== 200) return this.$message.error('获取用户列表失败！')
      this.userList = result.data.rows
      this.total = result.data.records
    },
    handleSizeChange(pageSize) {
      this.queryInfo.pagesize = pageSize
      this.getUserList()
    },
    handleCurrentChange(pageNo) {
      this.queryInfo.pagenum = pageNo
      this.getUserList()
    },
    async handleStatusChange(userInfo) {
      const { data: result } = await this.$http.put(`/users/${userInfo.id}/status/${userInfo.mgStatus}`)
      if (result.status !== 200) {
        return this.$message.error(result.msg)
      }
      this.$message.success('更新用户状态成功！')
    },
    addDailogClosed() {
      this.$refs.addFormRef.resetFields()
    },
    addUser() {
      this.$refs.addFormRef.validate(async valid => {
        if (valid) {
          // 添加用户操作
          const { data: result } = await this.$http.post('/users', this.addForm)
          if (result.status === 200) {
            this.$message.success('添加用户成功！')
            this.addDialogVisible = false
            this.getUserList()
          } else {
            this.$message.error(result.msg)
          }
        }
      })
    },
    async showEditDialog(id) {
      const { data: result } = await this.$http.get(`/users/${id}`)
      if (result.status === 200) {
        this.editForm.id = id
        this.editForm.username = result.data.username
        this.editForm.mobile = result.data.mobile
        this.editForm.email = result.data.email
        this.editDialogVisible = true
      }
    },
    editDialogClosed() {
      this.$refs.editFormRef.resetFields()
    },
    editUserInfo() {
      this.$refs.editFormRef.validate(async valid => {
        if (valid) {
          const { data: result } = await this.$http.put(`/users/${this.editForm.id}`, {
            mobile: this.editForm.mobile,
            email: this.editForm.email
          })
          if (result.status === 200) {
            this.$message.success('更新用户信息成功！')
            this.getUserList()
            this.editDialogVisible = false
          } else {
            this.$message.error('更新用户信息失败！')
          }
        }
      })
    },
    removeUserInfo(id) {
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: result } = await this.$http.delete(`/users/${id}`)
        if (result.status === 200) {
          this.$message.success('删除用户信息成功！')
          this.getUserList()
        }
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },
    async showAssignDialog(userInfo) {
      this.userInfo = userInfo
      // 获取角色名称列表
      const { data: result } = await this.$http.get('/roles')
      if (result.status !== 200) {
        return this.$message.error('获取角色列表失败！')
      }
      this.roleList = result.data
      this.setRoleDialogVisible = true
    },
    assginDialogClosed() {
      this.selectedRoleId = ''
    },
    async assignRole() {
      if (this.selectedRoleId === '') {
        return this.$message.error('请选择需要分配的角色！')
      }
      const { data: result } = await this.$http.put(`/users/${this.userInfo.id}/roles/${this.selectedRoleId}`)
      if (result.status !== 200) {
        return this.$message.error('分配角色失败！')
      }
      this.$message.success('分配角色成功！')
      this.getUserList()
      this.setRoleDialogVisible = false
    }
  }
}
</script>

<style lang="less" scoped>
.el-table {
  margin-top: 15px;
  font-size: 12px;
}

.el-pagination {
  margin-top: 15px;
}
</style>
